<template>
  <div class="pet-reaction-config-page">
    <div class="header">
      <div>
        <h1>宠物反应配置</h1>
        <p>在这里管理和查看宠物的反应配置</p>
      </div>
      <div>
        <el-button type="success" icon="el-icon-plus" @click="openAddDialog">新增反应</el-button>
        <el-button type="primary" icon="el-icon-back" @click="goToHomepage">返回主页</el-button>
      </div>
    </div>
    <div class="content">
      <div v-if="loading" v-loading="loading" class="loading-placeholder"></div>
      <el-collapse v-else v-model="activeCollapseNames">
        <el-collapse-item 
          v-for="(group, behaviorId) in groupedConfigs"
          :key="behaviorId"
          :name="behaviorId">
          <template slot="title">
            <span class="collapse-title">{{ formatOwnerAction(behaviorId) }}</span>
            <el-tag size="small" class="collapse-tag">{{ group.length }} 项</el-tag>
          </template>
          <div class="collapse-content">
            <el-table
              :data="group"
              style="width: 100%"
              stripe>
              <el-table-column prop="id" label="ID" width="80"></el-table-column>
              <el-table-column prop="emotionType" label="狗狗情绪" min-width="120">
                <template slot-scope="scope">{{ formatDogEmotion(scope.row.emotionType) }}</template>
              </el-table-column>
              <el-table-column prop="reactionType" label="狗狗反应" min-width="120">
                <template slot-scope="scope">{{ formatDogReaction(scope.row.reactionType) }}</template>
              </el-table-column>
              <el-table-column prop="reactionText" label="反应文本" min-width="200"></el-table-column>
              <el-table-column prop="isEnabled" label="是否启用" width="100">
                <template slot-scope="scope">
                  <el-tag :type="scope.row.isEnabled ? 'success' : 'info'" size="small">{{ scope.row.isEnabled ? '启用' : '禁用' }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="durationSeconds" label="持续时间 (秒)" width="120"></el-table-column>
              <el-table-column label="操作" width="180">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="primary"
                    @click="openEditDialog(scope.row)">编辑</el-button>
                  <el-button
                    size="mini"
                    type="danger"
                    @click="handleDelete(scope.row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-collapse-item>
      </el-collapse>
       <div v-if="!loading && Object.keys(groupedConfigs).length === 0" class="empty-data">
          <p>没有获取到数据，或配置为空。</p>
      </div>
    </div>

    <!-- Add Reaction Dialog -->
    <el-dialog
      title="新增宠物反应"
      :visible.sync="addDialogVisible"
      width="30%"
      @close="resetAddForm">
      <el-form :model="newReaction" label-width="100px">
        <el-form-item label="主人行为">
          <el-select v-model="newReaction.behaviorType" placeholder="请选择主人行为">
            <el-option
              v-for="(label, value) in ownerActionMap"
              :key="value"
              :label="label"
              :value="Number(value)">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="狗狗情绪">
          <el-select v-model="newReaction.emotionType" placeholder="请选择狗狗情绪">
            <el-option
              v-for="(label, value) in dogEmotionMap"
              :key="value"
              :label="label"
              :value="Number(value)">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="狗狗反应">
          <el-select v-model="newReaction.reactionType" placeholder="请选择狗狗反应">
            <el-option
              v-for="(label, value) in dogReactionMap"
              :key="value"
              :label="label"
              :value="Number(value)">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="反应文本">
          <el-input v-model="newReaction.reactionText" type="textarea" :rows="2"></el-input>
        </el-form-item>
          <el-form-item label="是否启用">
            <el-switch v-model="newReaction.isEnabled"></el-switch>
          </el-form-item>
          <el-form-item label="持续时间 (秒)">
            <el-input-number v-model="newReaction.durationSeconds" :min="0" :max="3600"></el-input-number>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="createReaction">确 定</el-button>
      </span>
    </el-dialog>

    <!-- Edit Reaction Dialog -->
    <el-dialog
      title="编辑宠物反应"
      :visible.sync="editDialogVisible"
      width="30%"
      @close="resetEditForm">
      <el-form :model="currentEditReaction" label-width="100px">
        <el-form-item label="主人行为">
          <el-select v-model="currentEditReaction.behaviorType" placeholder="请选择主人行为" disabled>
            <el-option
              v-for="(label, value) in ownerActionMap"
              :key="value"
              :label="label"
              :value="Number(value)">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="狗狗情绪">
          <el-select v-model="currentEditReaction.emotionType" placeholder="请选择狗狗情绪">
            <el-option
              v-for="(label, value) in dogEmotionMap"
              :key="value"
              :label="label"
              :value="Number(value)">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="狗狗反应">
          <el-select v-model="currentEditReaction.reactionType" placeholder="请选择狗狗反应">
            <el-option
              v-for="(label, value) in dogReactionMap"
              :key="value"
              :label="label"
              :value="Number(value)">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="反应文本">
          <el-input v-model="currentEditReaction.reactionText" type="textarea" :rows="2"></el-input>
        </el-form-item>
          <el-form-item label="是否启用">
            <el-switch v-model="currentEditReaction.isEnabled"></el-switch>
          </el-form-item>
          <el-form-item label="持续时间 (秒)">
            <el-input-number v-model="currentEditReaction.durationSeconds" :min="0" :max="3600"></el-input-number>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveReaction">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getPetReactionConfigs, updatePetReactionConfig, createPetReactionConfig, deletePetReactionConfig } from '@/api/adminService';

export default {
  name: 'PetReactionConfigPage',
  data() {
    return {
      configs: [],
      loading: true,
      activeCollapseNames: [], // Default open all items
      addDialogVisible: false,
      editDialogVisible: false,
      newReaction: {
        behaviorType: null,
        emotionType: null,
        reactionType: null,
        reactionText: '',
        isEnabled: true,
        durationSeconds: 10,
      },
      currentEditReaction: {
        id: null,
        behaviorType: null,
        emotionType: null,
        reactionType: null,
        reactionText: '',
        isEnabled: false,
        durationSeconds: null, // Add new field
      },
      ownerActionMap: {
        1: '进入家里',
        2: '打开操作框',
        3: '让狗狗睡觉',
        4: '喂饭',
        5: '一起玩耍',
        6: '让狗狗休息',
        7: '更新场景图片',
        8: '用户双击狗狗',
        9: '用户在睡觉时双击狗狗',
        10: '用户在吃饭时双击狗狗',
        11: '用户在吃饭时拖动狗狗',
        12: '用户在睡觉时拖动狗狗',
        13: '用户打开狗粮大全',
        14: '用户看了狗狗列表',
        15: '用户点击了狗狗头像',
        16: '用户在页面中长时间没有反应',
        17: '用户切换场景',
        18: '用户上班',
      },
      dogEmotionMap: {
        1: '高兴',
        2: '期待',
        3: '好奇',
        4: '放松',
        5: '疲倦',
        6: '悲伤',
      },
      dogReactionMap: {
        1: '站立',
        2: '玩耍',
        3: '吃饭',
        4: '睡觉',
        5: '休息',
        6: '躺下',
        7: '等待',
        8: '伸展',
        9: '歪头',
        10: '打滚',
        11: '伤心',
      },
    };
  },
  computed: {
    groupedConfigs() {
      // Sort configs by ID before grouping
      const sortedConfigs = [...this.configs].sort((a, b) => a.id - b.id);
      return sortedConfigs.reduce((acc, config) => {
        const key = config.behaviorType;
        if (!acc[key]) {
          acc[key] = [];
        }
        acc[key].push(config);
        return acc;
      }, {});
    }
  },
  async mounted() {
    await this.fetchConfigs();
  },
  methods: {
    async fetchConfigs() {
      this.loading = true;
      try {
        const result = await getPetReactionConfigs();
        if (result.success) {
          this.configs = result.data;
          if (this.configs.length > 0) {
            // Wait for the DOM to update before setting active names
            this.$nextTick(() => {
              this.activeCollapseNames = Object.keys(this.groupedConfigs);
            });
          } else {
             this.$message.info('未找到任何配置项。');
          }
        } else {
          this.$message.error(result.message || '获取配置失败');
        }
      } catch (error) {
        this.$message.error('请求异常: ' + error.message);
      } finally {
        this.loading = false;
      }
    },
    formatOwnerAction(actionId) {
      return this.ownerActionMap[actionId] || `未知行为 (${actionId})`;
    },
    formatDogEmotion(emotionId) {
      return this.dogEmotionMap[emotionId] || `未知情绪 (${emotionId})`;
    },
    formatDogReaction(reactionId) {
      return this.dogReactionMap[reactionId] || `未知反应 (${reactionId})`;
    },
    openAddDialog() {
      this.resetAddForm();
      this.addDialogVisible = true;
    },
    async createReaction() {
      try {
        const result = await createPetReactionConfig(this.newReaction);
        if (result.success) {
          this.$message.success('宠物反应创建成功！');
          this.addDialogVisible = false;
          await this.fetchConfigs();
        } else {
          this.$message.error(result.message || '创建失败');
        }
      } catch (error) {
        this.$message.error('请求异常: ' + error.message);
      }
    },
    resetAddForm() {
      this.newReaction = {
        behaviorType: null,
        emotionType: null,
        reactionType: null,
        reactionText: '',
        isEnabled: true,
        durationSeconds: 10,
      };
    },
    openEditDialog(row) {
      this.currentEditReaction = { ...row }; // Create a shallow copy to avoid direct mutation
      this.editDialogVisible = true;
    },
    async saveReaction() {
      try {
        const { id, ...payload } = this.currentEditReaction;
        const result = await updatePetReactionConfig(id, payload);
        if (result.success) {
          this.$message.success('宠物反应更新成功！');
          this.editDialogVisible = false;
          await this.fetchConfigs(); // Refresh data after successful update
        } else {
          this.$message.error(result.message || '更新失败');
        }
      } catch (error) {
        this.$message.error('请求异常: ' + error.message);
      }
    },
    resetEditForm() {
      this.currentEditReaction = {
        id: null,
        behaviorType: null,
        emotionType: null,
        reactionType: null,
        reactionText: '',
        isEnabled: false,
        durationSeconds: null,
      };
    },
    async handleDelete(id) {
      try {
        await this.$confirm('此操作将永久删除该配置, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        const result = await deletePetReactionConfig(id);
        if (result.success) {
          this.$message.success('删除成功！');
          await this.fetchConfigs();
        } else {
          this.$message.error(result.message || '删除失败');
        }
      } catch (error) {
        if (error === 'cancel') {
          this.$message.info('已取消删除');
        } else {
          this.$message.error('请求异常: ' + (error.message || '未知错误'));
        }
      }
    },
    goToHomepage() {
      this.$router.push('/dogs');
    },
  },
};
</script>

<style scoped>
.pet-reaction-config-page {
  background-color: #f7f8fa; /* A soft, neutral background */
  min-height: 100vh;
}

.header {
  padding: 24px 32px;
  background-color: #fff;
  border-bottom: 1px solid #e5e7eb;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header h1 {
  margin: 0 0 8px 0;
  font-size: 28px;
  font-weight: 600;
  color: #1f2937;
}

.header p {
  margin: 0;
  color: #6b7280;
  font-size: 14px;
}

.content {
  padding: 24px 32px;
}

.loading-placeholder {
  height: 300px;
  width: 100%;
}

/* Flat Collapse Styles */
::v-deep .el-collapse {
  border: none;
}

::v-deep .el-collapse-item {
  margin-bottom: 16px;
  background-color: #fff;
  border-radius: 8px;
  border: 1px solid #e5e7eb;
  overflow: hidden; /* Ensures child elements conform to border-radius */
}

::v-deep .el-collapse-item__header {
  padding: 0 24px;
  border-bottom: none;
  height: 64px;
  line-height: 64px;
  font-size: 16px;
  font-weight: 500;
  transition: background-color 0.3s ease;
}

::v-deep .el-collapse-item__header.is-active {
  border-bottom: 1px solid #e5e7eb;
}

::v-deep .el-collapse-item__wrap {
  border-bottom: none;
  padding: 0;
}

::v-deep .el-collapse-item__arrow {
  font-size: 14px;
  font-weight: 600;
}

.collapse-title {
  flex: 1;
  color: #303133;
}

.collapse-tag {
  margin-left: 16px;
  background-color: #f0f2f5;
  color: #6b7280;
  font-weight: 500;
  border: none;
}

.collapse-content {
  padding: 0;
}

.el-table::before { 
  /* Removes the bottom border of the table */
  display: none; 
}

.empty-data {
  text-align: center;
  color: #909399;
  padding: 60px 0;
  background-color: #fff;
  border-radius: 8px;
  border: 1px solid #e5e7eb;
}
</style>
